package com.lestar.www.wuliancamtest.WulianCam;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lestar.www.wuliancamtest.R;
import com.realtek.simpleconfiglib.wulian.SimpleConfigController;
import com.wulian.lanlibrary.LanController;
import com.wulian.routelibrary.ConfigLibrary;
import com.wulian.routelibrary.common.ErrorCode;
import com.wulian.routelibrary.common.RouteApiType;
import com.wulian.routelibrary.common.RouteLibraryParams;
import com.wulian.routelibrary.controller.RouteLibraryController;
import com.wulian.routelibrary.controller.TaskResultListener;
import com.wulian.routelibrary.utils.MD5;
import com.wulian.siplibrary.api.SipController;
import com.wulian.siplibrary.api.SipHandler;
import com.wulian.siplibrary.api.SipMsgApiType;
import com.wulian.siplibrary.manage.SipCallSession;
import com.wulian.siplibrary.manage.SipManager;
import com.wulian.siplibrary.manage.SipMessage;
import com.wulian.siplibrary.manage.SipProfile;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * User: EEE
 * Date: 2016/8/2
 * Time: 11:05
 */
public class WulianCamManager {
    private static final String REAL_SERVER = "acs.wuliancloud.com:33443";
    private Context mContext;

    private final int LOGIN_STATE_UNLOGIN = 0x00; // 未登录
    private final int LOGIN_STATE_GATEWAY_LOGIN = 0x01; // gateway方式已登陆
    private final int LOGIN_STATE_WEB_LOGIN = 0x02; // web方式已登陆
    private int mLoginState = LOGIN_STATE_UNLOGIN; // 登陆状态

    private UserInfo mUserInfo;
    private String mBindSeed;

    private boolean isDeviceChecked = false;
    private boolean isWifiConfiged = false;

    private ConfigWiFiInfoModel mConfigWiFiInfoModel;

    private SipProfile mSipAccount = null;
    private SipReceiver mSipReceiver = null;

    private SimpleConfigController mSimpleConfigController = null;

    private static WulianCamManager ourInstance = new WulianCamManager();

    public static WulianCamManager getInstance(Context context) {
        if (ourInstance.mContext == null) {
            ourInstance.mContext = context.getApplicationContext();
            RouteLibraryController.setLibraryPath("pu.sh.gg");
            ConfigLibrary.setFirstParamerConfig(ourInstance.mContext, "lestar");
        }
        return ourInstance;
    }

    private WulianCamManager() {
    }

    public UserInfo getUserInfo() {
        return mUserInfo;
    }

    public Observable<UserInfo> gatewayLogin(final String gatewayId, final String gatewayPwd) {
        return Observable.create(new Observable.OnSubscribe<UserInfo>() {
            @Override
            public void call(final Subscriber<? super UserInfo> subscriber) {
                RouteLibraryController.setWulianAESLibraryPath(REAL_SERVER);
                RouteLibraryController.getInstance().doRequest(
                        mContext,
                        RouteApiType.USER_LOGIN_WLAIKAN,
                        RouteLibraryParams.UserWulianAiKan(gatewayId, gatewayPwd),
                        new TaskResultListener() {

                            @Override
                            public void OnSuccess(RouteApiType routeApiType, String json) {
                                try {

                                    JSONObject jsonData = new JSONObject(json);
                                    if (jsonData.isNull("retData")) {
                                        subscriber.onError(new Throwable("Login fail!"));
                                    } else {
                                        String realData = jsonData.getString("retData");
                                        mUserInfo = new Gson().fromJson(realData, UserInfo.class);
                                        subscriber.onNext(mUserInfo);
                                        mUserInfo.setPassword(MD5.MD52(gatewayPwd).substring(0, 16)); // for later use
                                        mLoginState = LOGIN_STATE_GATEWAY_LOGIN;
                                    }
                                } catch (Exception e) {
                                    subscriber.onError(e);
                                }

                                subscriber.onCompleted();
                            }

                            @Override
                            public void OnFail(RouteApiType routeApiType, ErrorCode errorCode) {
                                subscriber.onError(new Throwable(errorCode.getDescription()));
                            }
                        });
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<UserInfo> webLogin(final String userName, final String webPwd) {
        return Observable.create(new Observable.OnSubscribe<UserInfo>() {
            @Override
            public void call(final Subscriber<? super UserInfo> subscriber) {
                RouteLibraryController.getInstance().doRequest(mContext,
                        RouteApiType.V3_LOGIN,
                        RouteLibraryParams.V3Login(userName, webPwd),
                        new TaskResultListener() {

                            @Override
                            public void OnSuccess(RouteApiType routeApiType, String json) {
                                mUserInfo = new Gson().fromJson(json, UserInfo.class);
                                subscriber.onNext(mUserInfo);
                                mUserInfo.setPassword(webPwd); // for later use
                                mLoginState = LOGIN_STATE_WEB_LOGIN;
                                subscriber.onCompleted();
                            }

                            @Override
                            public void OnFail(RouteApiType routeApiType, ErrorCode errorCode) {
                                subscriber.onError(new Throwable(errorCode.getDescription()));
                            }
                        });
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<List<Device>> getDeviceList() {
        final String auth = getUserInfo().getAuth();
        return Observable.create(new Observable.OnSubscribe<List<Device>>() {
            @Override
            public void call(final Subscriber<? super List<Device>> subscriber) {
                RouteLibraryController.getInstance().doRequest(
                        mContext,
                        RouteApiType.V3_USER_DEVICES,
                        RouteLibraryParams.V3UserDevices(auth, "cmic"),
                        new TaskResultListener() {
                            @Override
                            public void OnSuccess(RouteApiType routeApiType, String json) {
                                try {
                                    JSONArray OwnedDeviceListJson = new JSONObject(json).getJSONArray("owned");
                                    JSONArray SharedDeviceListJson = new JSONObject(json).getJSONArray("shared");
                                    List<Device> devices = new ArrayList<>();
                                    for (int i = 0; i < OwnedDeviceListJson.length(); i ++) {
                                        Device device = new Gson().fromJson(OwnedDeviceListJson.getString(i),
                                                Device.class);
                                        device.setUsername(device.getDid()); // Temporarily equivalent device id
                                        device.setIs_BindDevice(true);
                                        devices.add(device);
                                    }
                                    for (int i = 0; i < SharedDeviceListJson.length(); i ++) {
                                        Device device = new Gson().fromJson(SharedDeviceListJson.getString(i),
                                                Device.class);
                                        device.setUsername(device.getDid()); // Temporarily equivalent device id
                                        device.setIs_BindDevice(false);
                                        devices.add(device);
                                    }
                                    subscriber.onNext(devices);
                                    subscriber.onCompleted();
                                } catch (JSONException e) {
                                    subscriber.onError(e);
                                }
                            }

                            @Override
                            public void OnFail(RouteApiType routeApiType, ErrorCode errorCode) {
                                subscriber.onError(new Throwable(errorCode.getDescription()));
                            }
                        });
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    /** get bind seed if success */
    public Observable<String> bindCheck(final String deviceId) {
        final String auth = getUserInfo().getAuth();
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                RouteLibraryController.getInstance().doRequest(mContext,
                        RouteApiType.V3_BIND_CHECK,
                        RouteLibraryParams.V3BindCheck(auth, deviceId),
                        new TaskResultListener() {
                            @Override
                            public void OnSuccess(RouteApiType routeApiType, String json) {
                                try {
                                    JSONObject jsonObject = new JSONObject(json);
                                    String seed = jsonObject.isNull("seed") ? "" : jsonObject
                                            .getString("seed");
                                    if (!TextUtils.isEmpty(seed)) {
                                        String timestamp = jsonObject.isNull("timestamp") ? ""
                                                : jsonObject.getString("timestamp");
                                        seed = RouteLibraryParams.getDecodeString(seed, timestamp);
                                        if (TextUtils.isEmpty(seed)) {
                                            subscriber.onError(new Throwable("Unknown error"));
                                        } else {
                                            subscriber.onNext(seed);
                                            mBindSeed = seed;
                                            isDeviceChecked = true;
                                            subscriber.onCompleted();
                                        }
                                    } else {
                                        subscriber.onError(new Throwable("Device is bound by the other people"));
                                    }
                                } catch (JSONException e) {
                                    subscriber.onError(e);
                                }
                            }

                            @Override
                            public void OnFail(RouteApiType routeApiType, ErrorCode errorCode) {
                                subscriber.onError(new Throwable(errorCode.getDescription()));
                            }
                        });
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    /** get current wifi wifiSSID */
    public String getCurrentWifiSSID(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            WifiInfo info = wifiManager.getConnectionInfo();
            if (info != null) {
                String wifiSSID = info.getSSID().replace("\"", "");
                if (!TextUtils.isEmpty(wifiSSID)) {
                    ScanResult sResult = null;

                    for (ScanResult scanResult : wifiManager.getScanResults()) {
                        if (scanResult.SSID.equalsIgnoreCase(wifiSSID)) {
                            sResult = scanResult;
                            break;
                        }
                    }
                    if (DirectUtils.isAdHoc(sResult.capabilities)) {
                        Toast.makeText(context,
                                "AdHoc is not supported by Android platform yet!",
                                Toast.LENGTH_LONG).show();
                        return "";
                    }
                    if (TextUtils.isEmpty(wifiSSID) || info.getHiddenSSID()) {
                        Toast.makeText(context, "Confirm Wi-Fi is not hidden",
                                Toast.LENGTH_LONG).show();
                        return "";
                    }
                    if (info.getIpAddress() == 0) {
                        Toast.makeText(context, "Allocating IP, please wait a moment",
                                Toast.LENGTH_LONG).show();
                        return "";
                    }

                    if (mConfigWiFiInfoModel == null)
                        mConfigWiFiInfoModel = new ConfigWiFiInfoModel();
                    mConfigWiFiInfoModel.setWifiName(wifiSSID);

                    mConfigWiFiInfoModel.setBssid(sResult.BSSID);
                    mConfigWiFiInfoModel.setSecurity(DirectUtils.getStringSecurityByCap(sResult.capabilities));

                    Toast.makeText(context, "get wifi name success",
                            Toast.LENGTH_LONG).show();
                    isWifiConfiged = true;
                    return wifiSSID;
                }
            }
        }
        return "";
    }

    private boolean startConfigController(final String wifiName, final String wifiPwd, final String bssid) {
        if (mSimpleConfigController != null)
            return false;
        mSimpleConfigController = new SimpleConfigController();
        mSimpleConfigController.initData(mContext);
        mSimpleConfigController.StartConfig(wifiName, wifiPwd, bssid);
        return true;
    }

    private Observable<String> searchDeviceByMultiCastOb(final String targetDeviceId) {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo == null) {
                    subscriber.onError(new Throwable("fail get wifi info"));
                }
                final String localMac = wifiInfo.getMacAddress();
                if (TextUtils.isEmpty(localMac)) {
                    subscriber.onError(new Throwable("fail get mac address"));
                }
                RouteLibraryController.getInstance().doRequest(mContext,
                        RouteApiType.getAllDeviceInformationByMulticast,
                        RouteLibraryParams.getAllDeviceInformation(localMac),
                        new TaskResultListener() {
                            @Override
                            public void OnSuccess(RouteApiType routeApiType, String json) {
                                for (DeviceDescriptionModel deviceDescriptionModel : XMLHandler
                                        .getDeviceList(json)) {
                                    String deviceId = deviceDescriptionModel.getSipaccount();
                                    deviceId = deviceId.substring(deviceId.indexOf("cmic"), deviceId.indexOf("@"));
                                    if (deviceId.equalsIgnoreCase(targetDeviceId)) {
                                        final String deviceRealIP = deviceDescriptionModel.getRemoteIP();
                                        subscriber.onNext(deviceRealIP);
                                        subscriber.onCompleted();
                                        return;
                                    }
                                }
                                subscriber.onError(new Throwable("局域网内未找到指定设备"));
                            }

                            @Override
                            public void OnFail(RouteApiType routeApiType, ErrorCode errorCode) {
                                subscriber.onError(new Throwable(errorCode.getDescription()));
                            }
                        }
                );

            }
        });
    }

    private Observable<String> bindSeedSetOb(final String deviceIP, final String deviceId) {
        if (mConfigWiFiInfoModel == null)
            return null;
        final String seed = mConfigWiFiInfoModel.getSeed();
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                mSimpleConfigController.stopConfig();
                LanController.stopRequest();
                RouteLibraryController.getInstance().doRequest(
                        mContext, RouteApiType.BindSeedSet,
                        RouteLibraryParams.BindSeedSet(deviceIP, deviceId, seed), new TaskResultListener() {
                            @Override
                            public void OnSuccess(RouteApiType routeApiType, String s) {
                                subscriber.onNext("BindSeedSet success");
                                subscriber.onCompleted();
                            }

                            @Override
                            public void OnFail(RouteApiType routeApiType, ErrorCode errorCode) {
                                subscriber.onError(new Throwable(errorCode.getDescription()));
                            }
                        });
            }
        });
    }

    private Observable<String> checkBindResultOb(final String auth, final String deviceId) {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                RouteLibraryController.getInstance().doRequest(
                        mContext, RouteApiType.V3_BIND_RESULT,
                        RouteLibraryParams.V3BindResult(auth, deviceId), new TaskResultListener() {
                            @Override
                            public void OnSuccess(RouteApiType routeApiType, String json) {
                                try {
                                    JSONObject jsonObject = new JSONObject(json);
                                    int bindResult = jsonObject.isNull("result") ? 0 : jsonObject
                                            .getInt("result");
                                    if (bindResult == 1) {
                                        subscriber.onNext("v3 bind success");
                                        subscriber.onCompleted();
                                    } else
                                        subscriber.onError(new Throwable("v3 bind fail"));

                                } catch (JSONException e) {
                                    subscriber.onError(e);
                                }
                            }

                            @Override
                            public void OnFail(RouteApiType routeApiType, ErrorCode errorCode) {
                                subscriber.onError(new Throwable(errorCode.getDescription()));
                            }
                        });
            }
        });
    }

    /* 1. start config controller
    *  2. delay 30 sec
    *  3. start multiCast
    *  4. delay 90 sec
    *  5. stop config controller and stop multiCast
    *
    *  multiCast:
    *   1.
    * */
    public Observable<String> addDeviceByMulticast(final String deviceId) {
        final String wifiName = mConfigWiFiInfoModel.getWifiName();
        final String wifiPwd = mConfigWiFiInfoModel.getWifiPwd();
        final String bssid = mConfigWiFiInfoModel.getBssid();
        return Observable.just(startConfigController(wifiName, wifiPwd, bssid))
                .flatMap(new Func1<Boolean, Observable<Long>>() {
                    @Override
                    public Observable<Long> call(Boolean aBoolean) {
                        return Observable.timer(30, TimeUnit.SECONDS);
                    }
                }).flatMap(new Func1<Long, Observable<String>>() {
                    @Override
                    public Observable<String> call(Long aLong) {
                        return searchDeviceByMultiCastOb(deviceId).takeUntil(Observable.timer(90, TimeUnit.SECONDS));
                    }
                }).flatMap(new Func1<String, Observable<String>>() {
                    @Override
                    public Observable<String> call(String s) {
                        return bindSeedSetOb(s, deviceId);
                    }
                }).flatMap(new Func1<String, Observable<String>>() {
                    @Override
                    public Observable<String> call(String s) {
                        return checkBindResultOb(mUserInfo.getAuth(), deviceId).retry(15); // 失败重试15次
                    }
                })
                .doOnCompleted(new Action0() {
                    @Override
                    public void call() {
                        mSimpleConfigController.stopConfig();
                        LanController.stopRequest();
                    }
                })
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    public boolean preAddDevice(final String deviceId, final String wifiSSID, final String wifiPwd) {
        if (!isDeviceChecked || !isWifiConfiged || mConfigWiFiInfoModel == null)
            return false;
        mConfigWiFiInfoModel.setWifiName(wifiSSID);
        mConfigWiFiInfoModel.setWifiPwd(wifiPwd);

        mConfigWiFiInfoModel.setDeviceId(deviceId.toLowerCase(Locale.getDefault()));
        mConfigWiFiInfoModel.setAddDevice(true);
        mConfigWiFiInfoModel.setSeed(mBindSeed); // get from bind check
        DeviceType deviceType = DeviceType.getDevivceTypeByDeviceID(deviceId);
        mConfigWiFiInfoModel.setDeviceType(deviceType);

        // default QR config
        mConfigWiFiInfoModel.setQrConnect(true); // isQrConnect
        mConfigWiFiInfoModel.setSmartConnect(false); // isSmartConnect
        mConfigWiFiInfoModel.setConfigWiFiType(iCamConstants.CONFIG_BARCODE_WIFI_SETTING); // mCurrentConfigType
        return true;
    }

    public String getQRData() {
        if (mConfigWiFiInfoModel == null)
            return null;
        final String ssid = mConfigWiFiInfoModel.getWifiName();
        final String security = mConfigWiFiInfoModel.getSecurity();
        final String pwd = mConfigWiFiInfoModel.getWifiPwd();
        final String seed = mConfigWiFiInfoModel.getSeed();

        StringBuilder sb = new StringBuilder();
        sb.append(DirectUtils.getTypeSecurityByCap(security) + "\n");
        sb.append(ssid + "\n");
        if (DirectUtils.getTypeSecurityByCap(security) != DirectUtils.SECURITY_OPEN) {
            sb.append(RouteLibraryParams.EncodeMappingString(pwd));
            sb.append("\n");
        }
        sb.append(RouteLibraryParams.EncodeMappingString(seed));

        return sb.toString();
    }

    public Observable<String> loadCamPreview(Context context, final Device device, ISipListener listener) {
        return Observable.just(installSip(context, listener))
                .flatMap(new Func1<Boolean, Observable<Long>>() {
            @Override
            public Observable<Long> call(Boolean aBoolean) {
                if (!aBoolean)
                    return Observable.error(new Throwable("未登录"));
                else if (device.getOnline() != 1) {
                    return Observable.error(new Throwable("Device is offline"));
                } else
                    return Observable.interval(1, TimeUnit.SECONDS) // 每秒钟检查一次状态直到成功或者出错
                            .takeUntil(new Func1<Long, Boolean>() {
                        @Override
                        public Boolean call(Long aLong) {
                            int lastCode = SipController.getInstance().getAccountInfo(mSipAccount);
                            return (mSipAccount != null && lastCode != 100);
                        }
                    });
            }
        }).map(new Func1<Long, String>() {
            @Override
            public String call(Long aLong) {
                int lastCode = SipController.getInstance().getAccountInfo(mSipAccount);
                int stringId = 0;
                switch (lastCode) {
                    case 200:
                        // do nothing
                        break;
                    case 100:
                        stringId = R.string.sip_processing_waiting;
                        break;
                    case 401:
                        stringId = R.string.sip_unauthorized;
                        break;
                    case 404:
                        stringId = R.string.sip_offline;
                        break;
                    case 407:
                        stringId = R.string.sip_proxy_authentication_required;
                        break;
                    case 408:
                        stringId = R.string.sip_request_timeout;
                        break;
                    case 486:
                        stringId = R.string.sip_device_busy;
                        break;
                    case 503:
                        stringId = R.string.sip_service_unavailable;
                        break;
                    default:
                        stringId = R.string.sip_serve_error;
                        break;
                }
                if (stringId != 0)
                    return mContext.getResources().getString(stringId);
                else {
                    // To start get video stream
                    SipController.getInstance().makeCall(device.getUsername() + "@" + device.getSdomain(), mSipAccount);
                    return "success";
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    private boolean installSip(Context context, ISipListener listener) {
        if (mSipAccount == null && mSipReceiver == null) {
            mSipReceiver = new SipReceiver(listener);
            SipController.getInstance().CreateSip(mContext, false);
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(SipManager.GET_ACTION_SIP_CALL_CHANGED());
            intentFilter.addAction(SipManager.GET_ACTION_SIP_ALARM_MESSAGE_RECEIVED());
            context.registerReceiver(mSipReceiver, intentFilter);

            /** register a sip account */
            if (mLoginState != LOGIN_STATE_UNLOGIN) {
                mSipAccount = SipController.getInstance().registerAccount(
                        mUserInfo.getSuid(), mUserInfo.getSdomain(),
                        mUserInfo.getPassword());
                return true;
            }
            return false;
        }
        return true;
    }

    public void uninstallSip() {
        if (mSipAccount != null && mSipReceiver != null) {
            mContext.unregisterReceiver(mSipReceiver);// Close broadcast
            mSipReceiver = null;

            SipController.getInstance().unregistenerAccount(mSipAccount);// Logout
            mSipAccount = null;

            SipController.getInstance().DestroySip();// It must be the same thread
        }
    }

    private class SipReceiver extends BroadcastReceiver {
        private ISipListener listener;

        public SipReceiver(ISipListener listener) {
            this.listener = listener;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(SipManager.GET_ACTION_SIP_CALL_CHANGED())) {
                SipCallSession sipCallSession = intent.getParcelableExtra("call_info");
                if (sipCallSession != null && sipCallSession.getCallState() == SipCallSession.InvState.CONFIRMED) {
                    listener.onSipCallChanged(sipCallSession.getCallId());
                }

            } else if (action.equals(SipManager.GET_ACTION_SIP_ALARM_MESSAGE_RECEIVED())) {
                SipMessage sipMessage = (SipMessage) intent.getSerializableExtra("SipMessage");
                if (SipHandler.parseXMLData(sipMessage.getBody()) == SipMsgApiType.PUSH_ALARM_EVENT) {
                    listener.onSipAlarmReceived(sipMessage.getBody());
                }
            }
        }
    }

    public Observable<String> unbind(final String deviceId) {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
//                uninstallSip(); // if necessary ?
                RouteLibraryController.getInstance().doRequest(
                        mContext,
                        RouteApiType.V3_BIND_UNBIND,
                        RouteLibraryParams.V3BindUnbind(mUserInfo.getAuth(), deviceId),
                        new TaskResultListener() {
                            @Override
                            public void OnSuccess(RouteApiType routeApiType, String json) {
                                int unBindDeviceResult = 0;
                                try {

                                    JSONObject jsonData = new JSONObject(json);
                                    if (!jsonData.isNull("status")) {
                                        int status = jsonData.getInt("status");
                                        if (status == 1) {
                                            if (!jsonData.isNull("result")) {
                                                unBindDeviceResult = jsonData.getInt("result");
                                            }
                                        }
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                if (unBindDeviceResult == 1) {
                                    subscriber.onNext("UnBind Device   Success!!");
                                    subscriber.onCompleted();
                                } else {
                                    subscriber.onError(new Throwable("UnBind Device Fail!"));
                                }
                            }

                            @Override
                            public void OnFail(RouteApiType routeApiType, ErrorCode errorCode) {
                                subscriber.onError(new Throwable(errorCode.getDescription()));
                            }
                        });
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    
}
